﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MeTalker.Aide.Forms;
using System.Drawing;
using MeTalker.Aide.data;
using MeTalker.SDK.Core;
using MeTalker.Aide.DBUtility;
using MeTalker.Aide.Service;
using System.Reflection;

namespace MeTalker.Aide
{
    internal class MeApplicationBase : ApplicationContext, IWork
    {
        public void Refresh()
        {
            new frmMessage(DataFactory.Messages).ShowDialog();
            foreach (var form in Works)
            {
                try
                {
                    form.Value.InitData();
                }
                catch { }
            }
        }

        public void Stop(){}

        public bool Start() { return true; }

        protected NotifyIcon notifyIcon;

        protected MeContextMenuStrip contextMenuStrip;
        protected Timer mTimer;

        protected IDictionary<int, IWorkMode> Works = new Dictionary<int, IWorkMode>();


        protected IDictionary<int, ProcInfo> procs = new Dictionary<int, ProcInfo>();
        protected ShowFormHandler formHandler;

        protected System.Threading.Timer mTimerWin;

        protected ToolStripMenuItem cMenuExit;
        protected ToolStripMenuItem cMenuHelp;
        protected ToolStripMenuItem cMenuCustomer;
        protected ToolStripMenuItem cMenuSetting;

        protected ToolStripMenuItem cMenuRemarks;
        protected ToolStripMenuItem cMenuSelf;
        protected ToolStripMenuItem cMenuShortLan;
        protected ToolStripMenuItem cMenuAutoReply;
        protected ToolStripMenuItem cMenuImport;
        protected ToolStripMenuItem cMenuWizard;
        protected ToolStripMenuItem cMenuData;
        protected ToolStripMenuItem cMenuCustomerMessage;
        protected ToolStripMenuItem cMenuLicense;

        protected ToolStripMenuItem cMenuabout;
        protected ToolStripMenuItem cMenuHelper;
        public MeApplicationBase()
        {
            InitializeComponent();
        }
        void InitializeComponent()
        {
            #region 菜单
            contextMenuStrip = new MeContextMenuStrip();

            cMenuShortLan = new ToolStripMenuItem();
            cMenuShortLan.Click += new EventHandler(ContextMenu_Click);
            cMenuShortLan.Text = "分类短语库";

            cMenuExit = new ToolStripMenuItem();
            cMenuExit.Click += new EventHandler(ContextMenu_Click);
            cMenuExit.Text = "退 出";

            cMenuabout = new ToolStripMenuItem();
            cMenuabout.Click += new EventHandler(ContextMenu_Click);
            cMenuabout.Text = "关于";

            cMenuHelper = new ToolStripMenuItem();
            cMenuHelper.Click += new EventHandler(ContextMenu_Click);
            cMenuHelper.Text = "详细帮助";

            cMenuHelp = new ToolStripMenuItem();
            cMenuHelp.Text = "帮 助";
            cMenuHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
                cMenuHelper,
                cMenuabout
            });



            cMenuCustomer = new ToolStripMenuItem();
            cMenuCustomer.Text = "客服管理";

            cMenuRemarks = new ToolStripMenuItem();
            cMenuRemarks.Click += new EventHandler(ContextMenu_Click);
            cMenuRemarks.Text = "顾客备注";

            cMenuSelf = new ToolStripMenuItem();
            cMenuSelf.Click += new EventHandler(ContextMenu_Click);
            cMenuSelf.Text = "自学短语";



            cMenuAutoReply = new ToolStripMenuItem();
            cMenuAutoReply.Click += new EventHandler(ContextMenu_Click);
            cMenuAutoReply.Text = "自动回复";

            cMenuImport = new ToolStripMenuItem();
            cMenuImport.Click += new EventHandler(ContextMenu_Click);
            cMenuImport.Text = "导入旺旺聊天记录";

            cMenuWizard = new ToolStripMenuItem();
            cMenuWizard.Click += new EventHandler(ContextMenu_Click);
            cMenuWizard.Text = "导购菜单";

            //cMenuData = new ToolStripMenuItem();
            //cMenuData.Click += new EventHandler(ContextMenu_Click);
            //cMenuData.Text = "数据漫游";

            cMenuCustomerMessage = new ToolStripMenuItem();
            cMenuCustomerMessage.Click += new EventHandler(ContextMenu_Click);
            cMenuCustomerMessage.Text = "顾客留言";

            cMenuLicense = new ToolStripMenuItem();
            cMenuLicense.Click += new EventHandler(ContextMenu_Click);
            cMenuLicense.Text = "查看许可";
            cMenuCustomer.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
                cMenuShortLan,
                cMenuRemarks,
                cMenuSelf,
                cMenuAutoReply,
                cMenuImport,
                new ToolStripSeparator(),
                cMenuWizard,
                cMenuCustomerMessage,
                new ToolStripSeparator(),
                //cMenuData ,
                cMenuLicense
            });
            cMenuSetting = new ToolStripMenuItem();
            cMenuSetting.Click += new EventHandler(ContextMenu_Click);
            cMenuSetting.Text = "系统设置";


            contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { cMenuHelp, cMenuCustomer, cMenuSetting, new ToolStripSeparator(), new ToolStripSeparator(), cMenuExit });

            #endregion

            notifyIcon = new NotifyIcon();
            notifyIcon.MouseClick += new MouseEventHandler(notifyIcon_MouseClick);
            notifyIcon.ContextMenuStrip = contextMenuStrip;
            notifyIcon.BalloonTipTitle = "系统提示";// System.Configuration.ConfigurationManager.AppSettings["notifytip"];
            notifyIcon.Text = "金兰旺旺智能客服为您服务";//System.Configuration.ConfigurationManager.AppSettings["notifytip"]; ;
            notifyIcon.BalloonTipText = "金兰旺旺智能客服已经最小到系统状态栏。";//System.Configuration.ConfigurationManager.AppSettings["notifytip"];
            notifyIcon.Icon = new Icon(FileFactory.BaseDirectory + "icons/icon.ico");
            notifyIcon.ShowBalloonTip(300);
            notifyIcon.Visible = true;
            notifyIcon.ShowBalloonTip(3000);
            this.contextMenuStrip.ResumeLayout(false);
        }

        void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Type type = typeof(NotifyIcon);
                type.GetMethod("ShowContextMenu", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(this.notifyIcon, null);
            }
        }

        private void DisposeApp()
        {
            try
            {
                base.Dispose();
                AccessHelper.CloseConnect();
                if (mTimer != null)
                {
                    mTimer.Dispose();
                }
                mTimer = null;
            }
            catch { }
        }

        void SetFile()
        {
            try
            {
                UtilHelper.Update();
                SerializerFactory.SerializeFile<TradeFullinfos>(DataFactory.Trades, DataFactory.TRADE_FILE);
                SerializerFactory.SaveConfig();
                SerializerFactory.SerializeData(DataFactory.DataList);
                SerializerFactory.SerializeXml(DataFactory.Messages);
                SerializerFactory.SerializeXml(DataFactory.NodeLists.FileName, DataFactory.NodeLists);
                SerializerFactory.SerializeXml(DataFactory.CUSTOMER_FILE_NAME, DataFactory.ChatRecords);
            }
            catch
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Info("保存配置出错");
                Console.WriteLine("保存配置出错");
            }
        }

        protected void Close()
        {
            try
            {
                notifyIcon.Visible = false;
                string url = string.Format(UtilHelper.UPDATE_LICENSE_URL, UtilHelper.TYPE_USER_LOGOUT, DataFactory.User.SessionId, new Random().Next(), DataFactory.User.UserName);
                HttpClient.RequestHeart(url, new byte[] { 1 }, 1);
            }
            catch { }
            finally
            {
                try
                {
                    SetFile();
                    DisposeApp();
                }
                catch { }
                Application.Exit();
            }
        }

        protected void Start(ProcInfo proc, TalkerState state)
        {
            switch (state)
            {
                case TalkerState.AutoChatAid:
                    {
                        StartChat(proc);
                        break;
                    }
                case TalkerState.AutoMenuGuide:
                    {
                        StartGuide(proc);
                        break;
                    }
                case TalkerState.AutoQueryPieces:
                    {
                        StartQueryPieces(proc);
                        break;
                    }
            }
        }
        void StartQueryPieces(ProcInfo proc)
        {
            lock (Works)
            {
                if (!Works.ContainsKey(proc.Pid))
                {
                    CheckPieces service = new CheckPieces(proc, 60000, this);
                    service.WorkCallback = new WorkModeCallBack(WorkModeCallBack);// new CommandCallBack(CommandCallBack);
                    ((IWork)service).Start();
                    Works.Add(proc.Pid, service);
                }
            }
        }
        void CommandCallBack(object sender, TalkerState talkerState, object state)
        {
            try
            {
                TalkerForm talkerForm = state as TalkerForm;
                GuideService server = state as GuideService;
                if (talkerForm != null) {
                    lock (this)
                    {
                        if (Works.ContainsKey(talkerForm.WorkProcess.Pid))
                        {
#if DEBUG
                            Console.WriteLine("关闭辅聊" + talkerForm.WorkProcess.Alias);
#endif
                            Works.Remove(talkerForm.WorkProcess.Pid);
                            ((IWork)talkerForm).Stop();
                        }
                    }
                }
                if (server != null)
                {
                    lock (this)
                    {
                        if (Works.ContainsKey(server.WorkProcess.Pid))
                        {
#if DEBUG
                            Console.WriteLine("关闭会话" + server.WorkProcess.Alias);
#endif
                            Works.Remove(server.WorkProcess.Pid);
                            ((IWork)server).Stop();
                        }
                    }
                }
            }
            catch { }
        }

        void StartChat(ProcInfo proc)
        {
            lock (Works)
            {
                if (!Works.ContainsKey(proc.Pid))
                {
                    TalkerForm temp = new TalkerForm(proc, this);
                    temp.CmdCallBack = new CommandCallBack(CommandCallBack);
                    Works.Add(proc.Pid, temp);
                    AddMenuItem(proc);
                    ((IWorkMode)temp).Start();
                }
            }
        }

        protected void ChanageWorkMode(ProcInfo proc, TalkerState state)
        {
            try
            {
                Console.WriteLine("切换工作模式");
                IWorkMode work = null;
                if (Works.ContainsKey(proc.Pid))
                    work = Works[proc.Pid];
                else
                    return;
                Works.Remove(proc.Pid);
                work.Stop();
            }
            catch { }
            finally
            {
                if (proc != null)
                    proc.State = state;
            }
        }

        void WorkModeCallBack(object sender, Action action, TalkerState state)
        {
            try
            {
                IWorkMode workMode = sender as IWorkMode;
                if (workMode != null)
                {
                    if (state == TalkerState.Closed)
                    {
                        workMode.Stop();
                        if (Works.ContainsKey(workMode.WorkProcess.Pid))
                            Works.Remove(workMode.WorkProcess.Pid);
                    }
                }
            }
            catch { }
        }

        void StartGuide(ProcInfo proc)
        {
            lock (Works)
            {
                if (!Works.ContainsKey(proc.Pid))
                {
                    if (TalkerHelper.Check(proc.Alias) == true)
                    {
                        GuideService service = new GuideService(proc, UtilHelper.CHECK_TIME_OUT, this);
                        service.WorkCallback = new WorkModeCallBack(WorkModeCallBack);// new CommandCallBack(CommandCallBack);
                        ((IWork)service).Start();
                        Works.Add(proc.Pid, service);
                    }
                }
            }
        }


        protected void SetHeartbeat()
        {
            try
            {
                byte[] b = HttpClient.RequestHeart(string.Format(UtilHelper.HEART_URL, UtilHelper.TYPE_USER_HEART, DataFactory.User.UserName, new Random().Next()), new byte[] { 1 }, 1);
                if (b != null)
                {
                    string msg = Encoding.UTF8.GetString(b);
                    if (!string.IsNullOrEmpty(msg))
                    {
                        if (msg.Equals(UtilHelper.USER_INVALID) || msg.Equals(UtilHelper.LOGIN_OVER_VALID))
                        {
                            Close();
                        }
                        else if (msg.Contains("sid="))
                        {
                            DataFactory.User.SessionId = msg.Substring(4, msg.Length - 4);
                        }
                    }
                }
            }
            catch
            {
            }
        }
        
        #region 动态菜单
        protected void AddMenuItem(ProcInfo procInfo)
        {
            lock (contextMenuStrip)
            {
                if (DataFactory.User != null && DataFactory.User.IsSuccess)
                {
                    foreach (var item in contextMenuStrip.Items)
                    {
                        ToolStripMenuItem temp = item as ToolStripMenuItem;
                        if (temp != null && temp.Tag != null && (temp.Tag as ProcInfo) != null && (temp.Tag as ProcInfo).Account == procInfo.Account)
                        {
                            return;
                        }
                    }
                    UserConfig userconfig = null;
                    try
                    {
                        var dd = from temp in DataFactory.SystemConfig.UserConfigs where temp.Account.Equals(procInfo.Account) select temp;
                        userconfig = dd.FirstOrDefault();
                    }
                    catch { }
                    if (userconfig == null)
                    {
                        userconfig = new UserConfig() { WorkMode = TalkerState.AutoChatAid, Account = procInfo.Account, Alias = procInfo.Alias };
                        DataFactory.SystemConfig.UserConfigs.Add(userconfig);
                    }

                    ToolStripMenuItem tempMenuItem = new ToolStripMenuItem();
                    tempMenuItem.Image = new Bitmap(FileFactory.BaseDirectory+ "icons/iconx.gif");

                    ToolStripMenuItem menuItem1 = new ToolStripMenuItem("聊天辅助");
                    menuItem1.Click += new EventHandler(ContextMenu_Click);
                    menuItem1.Tag = procInfo;
                    menuItem1.Name = "menuChat";

                    menuItem1.Image = new Bitmap(FileFactory.BaseDirectory + "icons/iconx.gif"); // ((System.Drawing.Image)(resources.GetObject("kjlkToolStripMenuItem.Image")));

                    if (userconfig == null || userconfig != null && userconfig.WorkMode == TalkerState.AutoChatAid)
                    {
                        menuItem1.CheckState = CheckState.Checked;
                        tempMenuItem.Image = menuItem1.Image;
                    }


                    ToolStripMenuItem menuItem2 = new ToolStripMenuItem("菜单导购");
                    menuItem2.Click += new EventHandler(ContextMenu_Click);
                    menuItem2.Tag = procInfo;
                    menuItem2.Name = "menuWizard";
                    menuItem2.Image = new Bitmap(FileFactory.BaseDirectory + "icons/iconxred.gif");
                    if (userconfig != null && userconfig.WorkMode == TalkerState.AutoMenuGuide)
                    {
                        menuItem2.CheckState = CheckState.Checked;
                        tempMenuItem.Image = menuItem2.Image;
                    }


                    ToolStripMenuItem menuItem3 = new ToolStripMenuItem("自动查件");
                    menuItem3.Click += new EventHandler(ContextMenu_Click);
                    menuItem3.Tag = procInfo;
                    menuItem3.Name = "menuAuto";
                    menuItem3.Image = new Bitmap(FileFactory.BaseDirectory + "icons/iconxgold.gif");
                    if (userconfig != null && userconfig.WorkMode == TalkerState.AutoQueryPieces)
                    {
                        menuItem3.CheckState = CheckState.Checked;
                        tempMenuItem.Image = menuItem3.Image;
                    }

                    ToolStripMenuItem menuItem4 = new ToolStripMenuItem("不影响");
                    menuItem4.Click += new EventHandler(ContextMenu_Click);
                    menuItem4.Tag = procInfo;
                    menuItem4.Name = "menuAuto";
                    menuItem4.Image = new Bitmap(FileFactory.BaseDirectory + "icons/iconxgray.gif");
                    if (userconfig != null && userconfig.WorkMode == TalkerState.NoLicense)
                    {
                        menuItem4.CheckState = CheckState.Checked;
                        tempMenuItem.Image = menuItem4.Image;
                    }

                    tempMenuItem.Tag = procInfo;
                    tempMenuItem.Text = procInfo.Account;
                    tempMenuItem.Name = procInfo.Account;

                    tempMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { menuItem1, menuItem2, menuItem3, menuItem4 });

                    contextMenuStrip.Items.Insert(contextMenuStrip.Items.Count - 2, tempMenuItem);
                }
            }
        }

        protected void SetMenuItem(ProcInfo proc, bool isFlag)
        {
            try
            {
                ToolStripMenuItem menuMain = contextMenuStrip.Items[proc.Account] as ToolStripMenuItem;
                if (menuMain != null) { 
                
                }
            }
            catch { 
            
            }
        }

        protected void RemoveMenuItem(ProcInfo proc)
        {
            //contextMenuStrip.Items.RemoveByKey(proc.Account);
            lock (this)
            {
                contextMenuStrip.Items.RemoveByKey(proc.Account);
                if (procs != null && procs.ContainsKey(proc.Pid))
                {
                    procs.Remove(proc.Pid);
                }
            }
        }

        #endregion

        protected virtual void ContextMenu_Click(object sender, EventArgs e)
        {
            try
            {
                ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
                if (menuItem == cMenuExit)
                {
                    if (MeMessageBox.ShowQuestion("确认要退出系统吗？") == DialogResult.Yes)
                    {
                        try
                        {
                            List<KeyValuePair<int, IWorkMode>> temp = Works.ToList();
                            foreach (var vk in temp)
                            {
                                ((IWork)vk.Value).Stop();
                                Works.Remove(vk.Key);
                            }
                        }
                        catch { }
                        DisposeApp();
                        Close();
                    }
                }
                else if (menuItem == cMenuHelper)
                {
                    UtilHelper.RunBrowser(UtilHelper.HELP_BASE_URL + "69.html");
                }
                else if (menuItem == cMenuabout)
                {
                    new frmAbout().Show();
                }
                else if (menuItem == cMenuCustomer)
                {
                    new frmImportChatLog().Show();
                }
                else if (menuItem == cMenuSetting)
                {
                    new frmSetting().Show();
                }
                else if (menuItem == cMenuRemarks)
                {
                    new frmCustomRemarks().Show();
                }
                else if (menuItem == cMenuSelf)
                {
                    new frmSelfLearning().Show();
                }
                else if (menuItem == cMenuShortLan)
                {
                    ((IWork)this).Refresh();
                }
                else if (menuItem == cMenuAutoReply)
                {
                    new frmAutoReply().Show();
                }
                else if (menuItem == cMenuImport)
                {
                    new frmImportChatLog().Show();
                }
                else if (menuItem == cMenuWizard)
                {
                    new frmMenuNavigation().Show();
                }
                else if (menuItem == cMenuData)
                {

                }
                else if (menuItem == cMenuCustomerMessage)
                {
                    new frmCustomMessage().Show();
                }
                else if (menuItem == cMenuLicense)
                {
                    new frmLicense().Show();
                }
                else if (menuItem != null)
                {
                    ProcInfo proc = menuItem.Tag as ProcInfo;

                    ToolStripDropDownMenu parent = menuItem.GetCurrentParent() as ToolStripDropDownMenu;
                    for (int i = 0; i <= 3; i++)
                    {
                        (parent.Items[i] as ToolStripMenuItem).CheckState = CheckState.Unchecked;
                    }

                    UserConfig userConfig = null;
                    try
                    {
                        var d = from temp in DataFactory.SystemConfig.UserConfigs where temp.Account.Equals(proc.Account) select temp;
                        userConfig = d.FirstOrDefault();
                    }
                    catch { }
                    if (menuItem.ToString().Equals("聊天辅助"))
                    {
                        if (userConfig != null)
                            userConfig.WorkMode = TalkerState.AutoChatAid;
                        menuItem.CheckState = CheckState.Checked;

                        ChanageWorkMode(proc, TalkerState.AutoChatAid);
                    }
                    else if (menuItem.ToString().Equals("菜单导购"))
                    {
                        if (userConfig != null)
                            userConfig.WorkMode = TalkerState.AutoMenuGuide;
                        menuItem.CheckState = CheckState.Checked;
                        ChanageWorkMode(proc, TalkerState.AutoMenuGuide);

                    }
                    else if (menuItem.ToString().Equals("自动查件"))
                    {
                        menuItem.CheckState = CheckState.Checked;

                        if (userConfig != null)
                            userConfig.WorkMode = TalkerState.AutoQueryPieces;
                        ChanageWorkMode(proc, TalkerState.AutoQueryPieces);

                    }
                    else if (menuItem.ToString().Equals("不影响"))
                    {
                        if (userConfig != null)
                            userConfig.WorkMode = TalkerState.NoLicense;
                        menuItem.CheckState = CheckState.Checked;
                        ChanageWorkMode(proc, TalkerState.NoLicense);

                    }
                    contextMenuStrip.Items[proc.Account].Image = menuItem.Image;
                }
            }
            catch (Exception ex){
                if(UtilHelper.DEBUG)
                MuchInfo.Logs.MILog.Debug("右键菜单", ex);
            }
        }
    }
}